package logic

import (
	"common/model"
	"common/rabbitmq"
	"context"
	"errors"
	"fmt"
	"product_server/dao/dao_redis"
	product "product_server/proto"
	"time"
)

// 构建秒杀订单数据
func buildSeckillOrderData(userId int64, productInfo *model.MedicalProduct, spikesProductInfo *model.SeckillActivity) map[string]interface{} {
	return map[string]interface{}{
		"userId":        userId,
		"productId":     productInfo.Id,
		"activityId":    spikesProductInfo.Id,
		"seckillPrice":  spikesProductInfo.SeckillPrice,
		"originalPrice": spikesProductInfo.OriginalPrice,
		"orderType":     4, // 4表示秒杀订单类型
		"quantity":      1, // 秒杀通常限制每人一件
		"orderSn":       fmt.Sprintf("SK%s%d", time.Now().Format("20060102150405"), userId),
		"name":          productInfo.StoreName,
	}
}

// SnappedSpikesProduct 抢购秒杀商品
func (p *ProductServer) SnappedSpikesProduct(ctx context.Context, req *product.SnappedSpikesProductRequest) (*product.SnappedSpikesProductResponse, error) {
	// 查询秒杀商品信息
	spikesProductInfo, err := model.QuerySpikesProductInfo(req.SpikesProductId)
	if err != nil {
		return nil, err
	}

	// 获取商品基本信息
	productInfo, err := model.GetProductInfo(spikesProductInfo.ProductId)
	if err != nil {
		return nil, err
	}

	now := time.Now()
	// 判断是否在秒杀时间范围内
	if now.After(spikesProductInfo.StartTime) && now.Before(spikesProductInfo.EndTime) {
		// 更新秒杀商品状态
		err := model.UpdateSpikesProductStatus(req.SpikesProductId, 1)
		if err != nil {
			return nil, err
		}

		// 检查库存
		if SpikesProductLen := dao_redis.Len(req.SpikesProductId); SpikesProductLen <= 0 {
			return nil, errors.New("商品已被抢光")
		}

		// 扣减Redis中的库存
		err = dao_redis.SnappedSpikesProduct(req.SpikesProductId)
		if err != nil {
			return nil, err
		}

		// 构建订单数据并发送到RabbitMQ
		orderData := buildSeckillOrderData(req.UserId, productInfo, spikesProductInfo)
		rabbitmq.SimLpePublish(orderData)

		return &product.SnappedSpikesProductResponse{Success: "抢购成功"}, nil
	} else if now.Before(spikesProductInfo.StartTime) {
		return nil, errors.New("秒杀还未开始")
	} else {
		err := model.UpdateSpikesProductStatus(req.SpikesProductId, 2)
		if err != nil {
			return nil, err
		}
		return nil, errors.New("秒杀活动已结束")
	}
}
